package com.google.code.head2head.gwtmodules.client.fileupload;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.widgets.MessageBox;

public class ClassicalFileUploadPanel extends FormPanel {

	public ClassicalFileUploadPanel() {

		// Create a FormPanel and point it at a service.
		this.setAction("./fileUploadServlet");

		final HTML text = new HTML("");

		// Because we're going to add a FileUpload widget, we'll need to set the
		// form to use the POST method, and multipart MIME encoding.
		this.setEncoding(FormPanel.ENCODING_MULTIPART);
		this.setMethod(FormPanel.METHOD_POST);

		// Create a panel to hold all of the form widgets.
		VerticalPanel panel = new VerticalPanel();
		this.setWidget(panel);

		// Create a FileUpload widget.
		final FileUpload upload1 = new FileUpload();
		upload1.setName("image1");
		upload1.setTitle("Image 1");

		final FileUpload upload2 = new FileUpload();
		upload2.setName("image2");
		upload2.setTitle("Image 2");
		
		panel.add(new HTML("<br>1) Choose image files to upload</br>"));

		panel.add(text);
		panel.add(upload1);
		panel.add(upload2);

		// Add a 'submit' button.
		panel.add(new Button("Submit", new ClickListener() {
			public void onClick(Widget sender) {
				submit();
			}
		}));

		this.addFormHandler(new FormHandler() {
			public void onSubmit(FormSubmitEvent event) {
				text.setHTML("Uploading data to server...");
				if (upload1.getFilename().length() == 0
						|| upload2.getFilename().length() == 0) {
					MessageBox.alert("Message","You did not specify a filename!");
					event.setCancelled(true);
				} else if (!upload1.getFilename().toLowerCase()
						.endsWith(".jpg")
						|| !upload2.getFilename().toLowerCase()
								.endsWith(".jpg")) {
					MessageBox.alert("Message","Please specify a jpg file ending with '.jpg'.");
					event.setCancelled(true);
				}
			}

			public void onSubmitComplete(FormSubmitCompleteEvent event) {
				clear();
				add(new EntryInfoPanel());
				MessageBox.alert("Message",event.getResults());
			}
		});
	}
}
